package com.persondemo.videoappliction.ui.vip;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.persondemo.videoappliction.R;
import com.persondemo.videoappliction.bean.PersonSettingBean;
import com.persondemo.videoappliction.bean.UpimgBean;
import com.persondemo.videoappliction.component.ApplicationComponent;
import com.persondemo.videoappliction.component.DaggerHttpComponent;
import com.persondemo.videoappliction.event.MainEvent;
import com.persondemo.videoappliction.net.BaseApi;
import com.persondemo.videoappliction.photo.PhotoPickerActivity;
import com.persondemo.videoappliction.runtimepermissions.PermissionsManager;
import com.persondemo.videoappliction.runtimepermissions.PermissionsResultAction;
import com.persondemo.videoappliction.ui.base.AppManager;
import com.persondemo.videoappliction.ui.base.BaseActivity;
import com.persondemo.videoappliction.ui.vip.contract.SettingContract;
import com.persondemo.videoappliction.ui.vip.presenter.SettingPresenter;
import com.persondemo.videoappliction.utils.ImageLoaderUtil;
import com.persondemo.videoappliction.utils.PreferenceUtil;
import com.persondemo.videoappliction.utils.T;
import com.persondemo.videoappliction.widget.ClearEditText;

import org.simple.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;


/**
 * Created by Administrator on 2018/4/19.
 * 个人信息设置
 */

public class PersonSettingActivity extends BaseActivity<SettingPresenter> implements SettingContract.View {
    @BindView(R.id.setting_head_img)
    CircleImageView settingHeadImg;
    @BindView(R.id.me_setting)
    RelativeLayout meSetting;
    @BindView(R.id.aaaa)
    TextView aaaa;
    @BindView(R.id.nichen_relate)
    RelativeLayout nichenRelate;
    @BindView(R.id.bbbb)
    TextView bbbb;
    @BindView(R.id.sex_relate)
    RelativeLayout sexRelate;
    String nichen = "";
    @BindView(R.id.person_nichen)
    TextView personNichen;
    @BindView(R.id.person_sex)
    TextView personSex;
    @BindView(R.id.push_toggle)
    ToggleButton pushToggle;
    @BindView(R.id.setting_push_relate)
    RelativeLayout settingPushRelate;
    @BindView(R.id.setting_liner)
    LinearLayout settingLiner;
    @BindView(R.id.username_relate)
    RelativeLayout usernameRelate;
    @BindView(R.id.password_relate)
    RelativeLayout passwordRelate;

    @BindView(R.id.password_name)
    EditText passwordName;
    @BindView(R.id.username_name)
    EditText usernameName;
    private String[] sexArry = new String[]{"女", "男"};// 性别选择
    File file;
    String fileName;
    private String avatar = "";//头像
    private int sex = 0;//性别 1 男 0 女
    private String username = "";
    private String imei = "";
    private String username_user = "";
    private String password = "";

    @Override
    public void onRetry() {

    }

    @Override
    public int getContentLayout() {
        return R.layout.module_activity_personsetting;
    }

    @Override
    public void initInjector(ApplicationComponent appComponent) {
        DaggerHttpComponent.builder()
                .applicationComponent(appComponent)
                .build()
                .inject(this);
    }

    @Override
    public void bindView(View view, Bundle savedInstanceState) {

    }

    @Override
    public void initData() {
        imei = PreferenceUtil.getString("imei", "");
        if (TextUtils.isEmpty(imei)) {
            T.showShort(PersonSettingActivity.this, "未获取到imei权限，请从设置打开授予权限！");
            return;
        }
        sex = PreferenceUtil.getInt("sex", 0);
        if (sex == 0) {
            personSex.setText("女");
        } else {
            personSex.setText("男");
        }
        imei = PreferenceUtil.getString("imei", "");
        username = PreferenceUtil.getString("username", "");
        if (TextUtils.isEmpty(username)) {
            personNichen.setText("无名氏");
        } else {
            personNichen.setText(username);
        }
        if (!TextUtils.isEmpty(PreferenceUtil.getString("email", ""))) {
            usernameName.setText(PreferenceUtil.getString("email", ""));
        }

        avatar = PreferenceUtil.getString("avatar", "");
        ImageLoaderUtil.LoadImagelarge(PersonSettingActivity.this, avatar, settingHeadImg);
        Log.i("touxing", avatar);
        passwordName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().length() == 13) {
                    T.showShort(PersonSettingActivity.this, "最多输入13个字符！");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        usernameName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().length() == 13) {
                    T.showShort(PersonSettingActivity.this, "最多输入13个字符！");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @OnClick({R.id.me_setting, R.id.nichen_relate, R.id.sex_relate, R.id.setting_push_relate,
            R.id.username_relate, R.id.password_relate, R.id.setting_liner})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.me_setting:
                check();
                break;
            case R.id.nichen_relate:
                setNickname();
                break;
            case R.id.sex_relate:
                showSexChooseDialog();
                break;
            case R.id.setting_push_relate:
                if (pushToggle.isChecked() == true) {
                    JPushInterface.stopPush(getApplicationContext());
                } else {
                    JPushInterface.resumePush(getApplicationContext());
                }
                break;
            case R.id.setting_liner:
                if (mPresenter != null) {
                    showLoadingDialog();
                    username = personNichen.getText().toString();
                    username_user = usernameName.getText().toString().trim();
                    password = passwordName.getText().toString().trim();
                    mPresenter.upperson(avatar, username, sex, imei, username_user, password);
                }
                break;
//            case R.id.username_relate:
//                break;
//            case R.id.password_relate:
//                break;
        }
    }

    private void check() {
        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(PersonSettingActivity.this, new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA
        }, new PermissionsResultAction() {
            @Override
            public void onGranted() {
                go();
            }

            @Override
            public void onDenied(String permission) {
                T.showShort(PersonSettingActivity.this, "用户拒绝授权");
            }
        });
    }

    private void go() {
        Intent intent = new Intent(PersonSettingActivity.this, PhotoPickerActivity.class);
        intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, true);
        intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, PhotoPickerActivity.MODE_MULTI);
        intent.putExtra(PhotoPickerActivity.EXTRA_MAX_MUN, 1);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                ArrayList<String> result = data.getStringArrayListExtra(PhotoPickerActivity.KEY_RESULT);
                yasuo(result);
                Log.i("lidaming", "tupian:" + result.size() + result.toString());
            }
        }
    }

    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/Luban/image/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }

    private void yasuo(ArrayList<String> photos) {
        ImageLoaderUtil.LoadImage(PersonSettingActivity.this, photos.get(0), settingHeadImg);
        Luban.with(this)
                .load(photos)
                .ignoreBy(100)
                .setTargetDir(getPath())
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {
                        Log.i("lidaming", "11");
                        if (mPresenter != null) {
                            RequestBody requestFile =
                                    RequestBody.create(MediaType.parse("multipart/form-data"), file);
                            MultipartBody.Part body =
                                    MultipartBody.Part.createFormData("imgs", file.getName(), requestFile);
                            showLoadingDialog("图片上传中。。。");
                            mPresenter.upimgdata(body);

                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                }).launch();
    }

    private void setNickname() {
        AlertDialog.Builder builder = new AlertDialog.Builder(PersonSettingActivity.this);
        final ClearEditText nickname_input;
        final AlertDialog dialog;
        View dialgview = LayoutInflater.from(PersonSettingActivity.this).inflate(R.layout.person_nickname_dilog_layout, null, false);
        dialog = builder.setView(dialgview).create();
        if (dialog.isShowing()) {
            dialog.dismiss();
        } else {
            dialog.show();
        }
        nickname_input = (ClearEditText) dialgview.findViewById(R.id.dilog_nickname_reset_input);
        nickname_input.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().trim().length() == 8) {
                    T.showShort(PersonSettingActivity.this, "昵称长度最多8个字");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        dialgview.findViewById(R.id.dilog_nickname_reset_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
        dialgview.findViewById(R.id.dilog_nickname_reset_comfrim).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nichen = nickname_input.getText().toString().trim();
                personNichen.setText(nichen);
                dialog.dismiss();
            }
        });
    }

    /* 性别选择框 */
    private void showSexChooseDialog() {
        int a = 0;
        if (PreferenceUtil.getInt("sex", 0) == 0) {
            a = 0;
        } else {
            a = 1;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);// 自定义对话框
        builder.setSingleChoiceItems(sexArry, a, new DialogInterface.OnClickListener() {// 2默认的选中

            @Override
            public void onClick(DialogInterface dialog, int which) {// which是被选中的位置
                personSex.setText(sexArry[which]);
                if (sexArry[which].equals("男")) {
                    sex = 1;
                } else {
                    sex = 0;
                }
                dialog.dismiss();// 随便点击一个item消失对话框，不用点击确认取消
            }
        });
        builder.show();// 让弹出框显示
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    @Override
    public void imgdata(UpimgBean upimgBean) {
        hideLoadingDialog();
        if (upimgBean.getStatus() == 1) {
            PreferenceUtil.put("avatar", upimgBean.getData());
            avatar = upimgBean.getData();
        } else {
            T.showShort(PersonSettingActivity.this, upimgBean.getMsg());
        }
    }

    @Override
    public void persondata(PersonSettingBean personSettingBean) {
        hideLoadingDialog();
        if (personSettingBean.getStatus() == 1) {
            T.showShort(PersonSettingActivity.this, "修改成功！");
            PreferenceUtil.put("username", username);
            PreferenceUtil.put("sex", sex);
            PreferenceUtil.put("avatar", avatar);
            EventBus.getDefault().post(new MainEvent("更新用户信息"));
            AppManager.getAppManager().finishActivity();
        } else {
            T.showShort(PersonSettingActivity.this, personSettingBean.getMsg());
        }
    }

}
